package dao

import (
	"encoding/json"
	"git.supremind.info/product/box/vehicle/common"
	"git.supremind.info/product/box/vehicle/global"
	"git.supremind.info/product/box/vehicle/internal/dao/req"
	"git.supremind.info/product/box/vehicle/internal/util"
	"strconv"
	"time"
)

type UpgradeDeb struct {
	ID          uint      `gorm:"primary_key;auto_increment;not null" json:"id"`
	Version     string    `gorm:"version" json:"version"`
	JsonContent string    `gorm:"json_content" json:"jsonContent"`
	Source      string    `gorm:"source" json:"source"`
	CreateTime  util.Time `gorm:"create_time" json:"createTime"`
	UpdateTime  util.Time `gorm:"update_time" json:"updateTime"`
}

func (t *UpgradeDeb) TableName() string {
	return "upgrade_deb"
}

func GetUpgradeDebList() (list []UpgradeDeb) {
	DB.Debug().Model(&UpgradeDeb{}).Order("create_time desc").Find(&list)
	return list
}

func SaveUpgradeDeb(request req.SaveUpgradeDebReq) (err error) {
	content := struct {
		FileUrl string `json:"fileUrl"`
		Type    string `json:"type"`
	}{request.FileUrl, request.Type}

	now := time.Now()
	var deb = &UpgradeDeb{
		Version:     request.Version,
		JsonContent: util.JsonStr(content),
		Source:      "盒子上传升级包",
		CreateTime:  util.Time(now),
		UpdateTime:  util.Time(now),
	}
	DB.Debug().Create(deb)
	return err
}

func DeleteUpgradeVersion(request req.DelUpgradeDebReq) (err error) {
	DB.Debug().Where("id in ?", request.IDs).Delete(&UpgradeDeb{})
	return err
}

func DoUpgrade(request req.UpgradeBoxReq) (err error) {
	now := time.Now()
	var log = &UpgradeLog{
		Version:        request.Version.BoxSoftware.Version,
		UpgradeModules: util.JsonStr(request),
		CreateTime:     util.Time(now),
		UpdateTime:     util.Time(now),
	}
	DB.Debug().Create(log)
	common.Logger.Info("UpgradeLog:", util.JsonStr(log))
	request.Version.UpgradeId = strconv.Itoa(int(log.ID))

	url := global.VmrSetting.Host + "/v1/box/upgrade"
	res, err := util.PostData(url, request)
	common.Logger.Info("request url:", util.JsonStr(res))
	return err
}

//SDK升级
func DoSdkUpgrade(request req.UpdateSdkVo) (err error) {
	now := time.Now()
	var log = &UpgradeLog{
		Version:        request.Version,
		UpgradeModules: util.JsonStr(request),
		CreateTime:     util.Time(now),
		UpdateTime:     util.Time(now),
	}
	DB.Debug().Create(log)
	common.Logger.Info("UpgradeLog:", util.JsonStr(log))
	request.UpgradeId = strconv.Itoa(int(log.ID))

	url := global.VmrSetting.Host + "/v1/system/update_sdk"
	res, err := util.PostData(url, request)
	common.Logger.Info("request url:", util.JsonStr(res))
	return err
}

func (t *UpgradeDeb) ToJsonStr() string {
	marshal, err := json.Marshal(t)
	if err != nil {
		return ""
	}
	return string(marshal)
}
